package eva.savant.core.service

import org.springframework.beans.factory.annotation.Autowired

import java.text.SimpleDateFormat

class TSEntity {

  String sociedadId= ''

  Integer ALTA= 1

  Integer BAJA= 0

  @Autowired
  EntityService entityService

  public <T> T merge(T entity) {

    return entityService.merge(entity)
  }

  public void delete(Object entity) {

    entityService.delete(entity)
  }

  public <T> T remove(T entity) {

    return entityService.remove(entity)
  }

  public <T> T get(Class <T> tClass, Object primaryKey) {

    return entityService.find(tClass, primaryKey)
  }

  public <T> T get(Class <T> tClass, Object... values) {

    def model= find(tClass, values)

    return model != null && model.size() > 0? model[0] : null
  }

  public <T> List<T> find(Class<T> tClass, Object... values) {

    def selectWhere= (String) values[0]

    values[0]= sociedadId

    def miWhere= selectWhere.split(':')



    def select= 'm'

    if(miWhere.length > 1) {

      def aux= miWhere[0].trim().split('\\(')

      select= aux.length > 1? aux[0] + '(m.' + aux[1] : 'm.'+miWhere[0].trim()
    }


    def where= miWhere.length > 1? miWhere[1] : selectWhere

    where= where.replaceAll('^\\s+|\\s+$',''); //println 'dsalida-'+where+'-'

    def aux= where.split(' ')

    def wheres= ''

    for(dat in aux) wheres= wheres + ( dat.indexOf('.') > 0? 'm.'+dat : dat ) + ' '


    wheres= wheres.trim()
    //println 'wheres: '+wheres

    def cont= 2, res= ''

    char car= '?'


    for(int i = 0; i < wheres.length(); i++) {

      def c= wheres.charAt(i); res =  res + c

      if(c==car) { res =  res + cont;  cont++ }
    }
    // println 'res:-'+res+'-'

    res= 'm.sociedadId=?1 and m.operacionId > 0' + ((res.length()> 0)? ' and ' : '') + res


    def queryString = 'select '+select+' from ' + tClass.canonicalName + ' m where ' + res



    println queryString + '\n ' +values

    return miWhere.length > 1? entityService.find(queryString,values) : entityService.find(tClass,queryString,values)
  }

  public static Date toStartDay(Date date) {

    def day= Calendar.instance; day.setTime(date)

    day.set(Calendar.HOUR_OF_DAY,00)

    day.set(Calendar.MINUTE,00)

    day.set(Calendar.SECOND,00)

    return day.time
  }

  public static String toDate(Long date, String format) {

    def sdf=new SimpleDateFormat(format)

    return sdf.format(new Date(date))
  }

}
